﻿using UnityEngine;
using System.Collections;

public class BundleAssetLoader:Loader
{
	private AssetBundle m_bundle = null;
	private AssetBundleRequest m_loadOpt = null;

	public BundleAssetLoader ()
		: base (Loader.LoaderType.BUNDLEASSET)
	{
		
	}

	protected override void Reset ()
	{
		base.Reset ();

		m_bundle = null;
		m_loadOpt = null;
	}

	public override void Load ()
	{
		base.Load ();

		if (string.IsNullOrEmpty (m_path)) {
			OnLoaded (null);
			return;
		}

		object[] arrParam = m_param as object[];
		if (arrParam.Length < 2) {
			return;
		}

		m_bundle = arrParam [0] as AssetBundle;
		System.Type type = arrParam [1] as System.Type;

		if (m_async) {
			m_loadOpt = m_bundle.LoadAssetAsync (m_path, type);
		} else {
			Object obj = m_bundle.LoadAsset (m_path, type);
			OnLoaded (obj);
		}
	}

	public override void Update (float dt)
	{
		if (m_state != LoaderState.LOADING) {
			return;
		}

		if (m_loadOpt.isDone) {
			OnLoaded (m_loadOpt.asset);
			m_loadOpt = null;
		} else {
			OnLoadProgress (m_loadOpt.progress);
		}
	}

	void OnLoaded (Object asset)
	{
		Debuger.Log ("Load {0} - {1} use {2}ms", m_path, m_async, m_watch.Elapsed.Milliseconds);

		OnLoadCompleted (asset);
	}
}